let res = [];

function dataforeach (data) {
  data.map(ele => {
    if (ele.children.length > 0) {
      // debugger
      dataforeach(ele.children);
      // return ele;
    } else {
      res.push({
        businessScopeId: ele.id
      })
    }
  })
  return res;
}




let result = [];
let res1 = "";

function find (data, id) {
  const flatList = flatArr(data);
  // let res1 = '';
  debugger
  getParent(flatList, id);
  // console.log(res1);
  return res1;
}

//  扁平化数组
function flatArr (data) {
  data.map(ele => {
    result.push({
      "id": ele.id,
      "parentId": ele.parentId,
    })
    flatArr(ele.children);
  })
  return result;
}

// 递归查找最外层parentId
function getParent (data, id) {
  for (let i = 0; i < data.length; i++) {
    const e = data[i];
    if (e.id === id) {
      debugger
      if (e.parentId === null) {
        res1 = e.id;
        debugger;
        return e.id;
        // return res1;
        // console.log('uuu', e.id);
      } else {
        getParent(data, e.parentId)
      }
    }
     else {
      continue;
    }
  }
  // console.log(res1, ' console.log(res1);');
  return res1;
}

// Label l = list.stream().filter( x -> Objects.equals(x.getLableId(), label.getParentId()) ).findFirst().get(); 


const arr = [
  {
    "id": 13,
    "title": "经营范围一",
    "parentId": null,
    "children": [
      {
        "id": 16,
        "title": "01",
        "parentId": 13,
        "children": [
          {
            "id": 592,
            "title": "11",
            "parentId": 16,
            "children": []
          }
        ]
      },
      {
        "id": 595,
        "title": "q",
        "parentId": 13,
        "children": []
      },
      {
        "id": 596,
        "title": "s",
        "parentId": 13,
        "children": []
      },
      {
        "id": 598,
        "title": "ddd",
        "parentId": 13,
        "children": []
      }
    ]
  },
  {
    "id": 15,
    "title": "经营范围三",
    "parentId": null,
    "children": [
      {
        "id": 18,
        "title": "03",
        "parentId": 15,
        "children": [
          {
            "id": 594,
            "title": "33",
            "parentId": 18,
            "children": []
          }
        ]
      }
    ]
  }
];

// console.log(dataforeach(arr));

console.log(find(arr, 15));